package com.hopes.bizz.risk.control.evaluate;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hopes.bizz.risk.common.constant.enums.RiskSysDictEnum;
import com.hopes.bizz.risk.control.bo.NegatedItem;
import com.hopes.bizz.risk.control.bo.RiskEffectEvaluationScore;
import com.hopes.bizz.risk.control.bo.RiskEvaluateBo;
import com.hopes.bizz.risk.control.entity.RiskMeasureTaskEntity;
import com.hopes.bizz.risk.control.entity.RiskObjectEntity;
import com.hopes.bizz.risk.control.entity.RiskUnitEntity;
import com.hopes.bizz.risk.control.service.RiskMeasureTaskService;
import com.hopes.bizz.risk.control.service.RiskObjectService;
import com.hopes.bizz.risk.control.service.RiskUnitService;
import com.hopes.boss.admin.api.resolver.DictResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @author lyb
 * @version 1.0
 * @description: 重大危险源缺少任意类型包保责任人任务。
 * @date 2023/7/6
 */
@Component
@Slf4j
@Order(1004)
public class RiskHazPrincipalRejectFactorHandler extends RiskRejectFactorHandler {

    @Resource
    private RiskObjectService riskObjectService;

    @Resource
    private RiskUnitService riskUnitService;

    @Resource
    private RiskMeasureTaskService riskMeasureTaskService;

    @Override
    protected NegatedItem doCalculate(RiskEvaluateBo riskEvaluateBo, NegatedItem negatedItem) {
        // 查询所有重大危险源下的单元的所有管控措施
        StringBuilder sb = new StringBuilder();
        List<RiskObjectEntity> hazardRiskObject = getHazardRiskObject();
        if (CollectionUtil.isEmpty(hazardRiskObject)) {
            sb.append("不存在重大危险源!");
        }
        RiskEffectEvaluationScore riskEffectEvaluationScore = riskEvaluateBo.getRiskEffectEvaluationScore();
        Map<Integer, Integer> riskGuaranteePrincipalTypeMap = riskEffectEvaluationScore.getRiskGuaranteePrincipalTypeMap();
        boolean score = Boolean.TRUE;
        for (RiskObjectEntity riskObject : hazardRiskObject) {
            String hazardName = riskObject.getHazardName();
            // 查询该单元下所有管控措施
            List<RiskUnitEntity> riskUnitList = getRiskUnitByRiskObjectId(riskObject.getId());
            List<Long> riskUnitIdList = riskUnitList.stream().map(RiskUnitEntity::getId).collect(Collectors.toList());
            List<RiskMeasureTaskEntity> riskMeasureTaskList = riskMeasureTaskService.getByRiskUnitIdList(riskUnitIdList);
            // 查询任务是否包含了所有包保责任人分类
            Map<Integer, List<RiskMeasureTaskEntity>> workTypeMap = riskMeasureTaskList.stream().collect(Collectors.groupingBy(RiskMeasureTaskEntity::getWorkType));
            for (int workType : riskGuaranteePrincipalTypeMap.keySet()) {
                List<RiskMeasureTaskEntity> riskMeasureTasks = workTypeMap.get(workType);
                String workTypeName = DictResolver.getItemLabelByValue(RiskSysDictEnum.risk_work_type, workType);
                // 没有该类型任务直接返回
                if (CollectionUtil.isEmpty(riskMeasureTasks)) {
                    score = Boolean.FALSE;
                    sb.append(hazardName).append(" 风险分析对象重大危险源没有配置").append(workTypeName).append(LINE_SEPARATOR);
                    continue;
                }
                // 判断任务项是否全覆盖
                Set<Integer> taskNumbers = riskMeasureTasks.stream().map(RiskMeasureTaskEntity::getTaskNum).collect(Collectors.toSet());
                Integer count = riskGuaranteePrincipalTypeMap.get(workType);
                if (count != taskNumbers.size()) {
                    score = Boolean.FALSE;
                    sb.append(hazardName).append(" 风险分析对象重大危险源没有全部覆盖 ").append(workTypeName).append(" 的 ").append(count).append("项任务， 缺失第");
                    for (int i = 1; i <= count; i++) {
                        if (!taskNumbers.contains(i)) {
                            sb.append(i).append("、");
                        }
                    }
                    sb.deleteCharAt(sb.length() - 1).append("项任务;").append(LINE_SEPARATOR);
                }
            }
        }
        negatedItem.setNegatedItemFour(score);
        if (sb.length() > 0) {
            negatedItem.setNegatedItemFourReason(sb.toString());
        }
        return doNextCalculate(riskEvaluateBo, negatedItem);
    }

    private List<RiskObjectEntity> getHazardRiskObject() {
        LambdaQueryWrapper<RiskObjectEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(RiskObjectEntity::getHazardSourceFlag, true);
        return riskObjectService.list(wrapper);
    }

    private List<RiskUnitEntity> getRiskUnitByRiskObjectId(Long riskObjectId) {
        LambdaQueryWrapper<RiskUnitEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(RiskUnitEntity::getRiskObjectId, riskObjectId);
        return riskUnitService.list(wrapper);
    }

    @Override
    protected Boolean isUse(RiskEffectEvaluationScore riskEffectEvaluationScore) {
        return riskEffectEvaluationScore.getRiskPrincipalFlag();
    }

}
